package com.sdu.game.websocket;


import com.sdu.game.controller.Shujuk;
import com.sdu.game.mapper.PlayerMapper;
import com.sdu.game.mapper.PlayerbMapper;
import com.sdu.game.mapper.RoomMapper;
import com.sdu.game.mapper.UserMapper;
import com.sdu.game.pojo.*;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@CrossOrigin//告诉浏览器允许别的网站访问我
public class Game {


    @Resource
    private GameRoom gameRoom;//用来调用websocket操作



    ConcurrentHashMap<String, Session> sessionList=gameRoom.getSessionPools();//当前游戏在线用户

    @Autowired
    RoomMapper roomMapper;



    @Autowired
    PlayerbMapper playerbMapper;

    @Autowired
    UserMapper userMapper;



    //玩家进房调用该连接进行座位分配
    //用户匹配进房使用"/webSocket/{sid}"

    //玩家进房后需要准备操作，通过http进行连接操作

    //玩家的准备信息，通过webSocket将准备信息返回给该房间内的所有玩家
    @RequestMapping("/zhilang/v1/game/ready")
    public String ready(int userId){





        //用户id
//        int userId=1;
        int roomId=1;

        List<Room> roomlist=roomMapper.selectByExample(null);//查询所有房间
        System.out.println(roomlist.toString());


        System.out.println("aawwwwwwwwwwwwwwwwwwwwwwwwwwwwwww");
        List<Playerb> playlistq=playerbMapper.selectByExample(null);

        System.out.println(playlistq);

        //对用户id进行房间座位分配，使用websocket将信息广播给全部用户
        ArrayList<Integer> userlist=new ArrayList<>();


        if(roomlist.size()>=1){
            //有房间的情况下判断是否有空余房间



            Room newroom=new Room();

            Room room=new Room();
            room=roomlist.get(roomlist.size()-1);





            System.out.println(room.toString());
            int v1=room.getUserIdOfVillager1();
            int v2=room.getUserIdOfVillager2();
            int w1=room.getUserIdOfWerewolf1();
            int w2=room.getUserIdOfWerewolf2();
            int wi=room.getUserIdOfWitch();
            int pr=room.getUserIdOfProphet();




            Map<String,Integer> us=new HashMap<>();



//            Map<String, Integer> ud=new HashMap<>();
            System.out.println(us.toString());

            ArrayList<String> ud=new ArrayList<>();

            us.put("v1",v1);
            us.put("v2",v2);
            us.put("w1",w1);
            us.put("w2",w2);
            us.put("wi",wi);
            us.put("pr",pr);

            //空值
            int sum=0;


            for(String key:us.keySet()){
                System.out.println(us.get(key));

                if (us.get(key)==1000){
                    ud.add(key);
                    sum=sum+1;
                }



            }
            System.out.println(ud.toString());
            System.out.println(sum);

            if (sum!=0){
                System.out.println("添加用户进去");
                String key=ud.get(0);
                us.put(key,userId);
                System.out.println(key);



                switch (key){
                    case "v1":
//                        System.out.println(room.getUserIdOfVillager1());
                        room.setUserIdOfVillager1(userId);
                        break;
                    case "v2":
                        room.setUserIdOfVillager2(userId);
                        break;
                    case "w1":
                        room.setUserIdOfWerewolf1(userId);
                        break;
                    case "w2":
                        room.setUserIdOfWerewolf2(userId);
                        break;
                    case "wi":
                        room.setUserIdOfWitch(userId);
                        break;
                    case "pr":
                        room.setUserIdOfProphet(userId);
                        break;
                }

                System.out.println("yyyyyyyyyyyyyyyyyyyyyy");
                System.out.println(room.getRoomId());
                System.out.println(room.getUserIdOfWitch());



                System.out.println("dsssssssssssss");
                for(String k:us.keySet()){
                    if (us.get(k)!=1000){

                        userlist.add(us.get(k));

                    }

                }
                System.out.println(userlist.toString());
                room.setTime("ddd");
                room.setDaytime(1);
                room.setRoomType("qq");


                roomId=room.getRoomId();

                int updateRow=roomMapper.updateByPrimaryKeySelective(room);

                System.out.println(updateRow);


            }else{



                //新建房间
                System.out.println("新建房间");
                Room roomd=new Room();
                int roomiq=room.getRoomId()+1;
                roomd.setRoomId(roomiq);
                roomd.setUserIdOfProphet(userId);
                roomd.setUserIdOfVillager1(1000);
                roomd.setUserIdOfVillager2(1000);
                roomd.setUserIdOfWerewolf1(1000);
                roomd.setUserIdOfWerewolf2(1000);
                roomd.setUserIdOfWitch(1000);

                roomId=roomd.getRoomId();

                int insertRow=roomMapper.insertSelective(roomd);

                System.out.println(insertRow);

            }





        }else{
            //新建房间
            System.out.println("新建房间");
            Room roomd=new Room();
            roomd.setRoomId(1000);
            roomd.setUserIdOfProphet(userId);
            roomd.setUserIdOfVillager1(1000);
            roomd.setUserIdOfVillager2(1000);
            roomd.setUserIdOfWerewolf1(1000);
            roomd.setUserIdOfWerewolf2(1000);
            roomd.setUserIdOfWitch(1000);

            roomId=roomd.getRoomId();

            int insertRow=roomMapper.insertSelective(roomd);

            System.out.println(insertRow);

            userlist.add(userId);




        }

        //上面给用户分配了房间，并得到房间号内的用户的全部ID
//        userlist保存当前房间所有用户的ID
//        将房间用户的座位号和id分给用户
        //根据用户顺序给用户赋予座位号
        int seat_id=userlist.size();//一个用户则只有当前，两个用户则第二
        if (userlist.size()==0){
            userlist.add(userId);
        }

        Playerb playerb=new Playerb();

        playerb.setUserId(userId);
        playerb.setRoomId(roomId);
        playerb.setSeatNumber(seat_id);
        playerb.setPlayStatus(0);//0是准备,1是开始
        playerb.setAli(1);//1是存活，默认活着

        //插入数据库
        int insertRow=playerbMapper.insertSelective(playerb);

        System.out.println("数据插入");
        System.out.println(insertRow);

        //向前端推送用户加入信息
//        查找用户表得到username，推送到前端

        HashMap<Integer,String>  usernamelist=new HashMap<>();
        ArrayList<String> messagelist=new ArrayList<>();


        for(int i=0;i<userlist.size();i++){
            int userk=userlist.get(i);

            UserExample userExample=new UserExample();
            UserExample.Criteria criteria=userExample.or();
            criteria.andUserIdEqualTo(userk);

            List<User> list=userMapper.selectByExample(userExample);//查找用户昵称

            System.out.println("ssqqqqqqqqqwdccccccccccc");
            System.out.println(list);

            PlayerbExample playerbExample=new PlayerbExample();
            PlayerbExample.Criteria criteriap=playerbExample.or();
            criteriap.andUserIdEqualTo(userk);

            List<Playerb> listp=playerbMapper.selectByExample(playerbExample);//查找座位号

            int se=listp.get(0).getSeatNumber();
            String username=list.get(0).getUsername();

            String seat=Integer.toString(se);
            String userkk=Integer.toString(userk);
            String message="1,"+ userkk+"," +username+","+seat;
            messagelist.add(message);

            usernamelist.put(userk,message);




        }




//        int userId,int RoomID
        //根据userId和RoomId
        //修改玩家表中玩家的游戏状态

        //查找该房间中的所有玩家编号
        //将当前所有玩家的状态返回给房间所有用户

        //userlist用户id
        //usernamelist,座位号+昵称



//给每个用户广播信息,给房间内的所有用户广播

        for(int i=0;i< userlist.size();i++){
            int userk=userlist.get(i);
            System.out.println(userk);
            String userkd=Integer.toString(userk);
            Session sessiond= sessionList.get(userkd);
//            String message=usernamelist.get(userk);

            for(int j=0;j<messagelist.size();j++){
                String message=messagelist.get(j);

                try {
                    gameRoom.sendMessage(sessiond, message);
                } catch(Exception e){
                    e.printStackTrace();
                    continue;
                }
            }



        }









        //当所有玩家都准备好的时候给该房间玩家进行角色分配,同时通过http给前端推送该房间用户角色信息

//        使用js数据保存信息传送,传送所有人的角色信息，以及是否跳转页面信息，前端http接受消息后跳转页面开始游戏。



//        for (Session session: sessionList.values()) {
//            System.out.println(session);
//
//            try {
//                gameRoom.sendMessage(session, Data_user);
//            } catch(Exception e){
//                e.printStackTrace();
//                continue;
//            }
//        }

        return "zhunsbsbbs";

    }




}